package com.Demo;

import java.util.Random;


public class mvmmv  {
    public static void main(String[] args) {
// 实例化业务类
        Service service = new Service();
// 分别创建两个线程
        MyThread1 t1 = new MyThread1(service);
        MyThread1 t3 = new MyThread1(service);
// 再产生一个Serivce
// service = new Service();
        MyThread2 t2 = new MyThread2(service);
// 分别启动两个线程
        t1.start();
        t2.start();
        t3.start();
    }
}
/**
 * 业务类
 */
class Service {
    /**
     * 业务方法：加锁
     */
    public synchronized void doSomething() {

        try {
            Thread.sleep(new Random().nextInt(5)); // 随机休眠
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 1; i <= 100; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
    }
    /**
     * 另外一个业务方法：这个不是同步方法。
     */
    public void doOtherthing() {
        try {
            Thread.sleep(new Random().nextInt(5)); // 随机休眠
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 1; i <= 100; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
    }
}
/**
 * 线程1调用doSomething()。
 */
class MyThread1 extends Thread {
    private Service serivce;
    public MyThread1(Service serivce) {
        this.serivce = serivce;
    }
    @Override
    public void run() {
// 调用业务类的业务方法doSomething();
        serivce.doSomething();
    }
}
/**
 * 线程2调用doOtherthing()
 */
class MyThread2 extends Thread {
    private Service serivce;

    public MyThread2(Service serivce) {
        this.serivce = serivce;
    }

    @Override
    public void run() {
// 调用业务类的业务方法doOtherthing();
        serivce.doOtherthing();
    }
}